package com.mayi.zds.service.imp;

import com.mayi.zds.dao.*;
import com.mayi.zds.dao.param.OrderQueryParam;
import com.mayi.zds.entity.Coupon;
import com.mayi.zds.entity.Order;
import com.mayi.zds.entity.OrderItem;
import com.mayi.zds.service.OrderService;
import com.mayi.zds.utils.ZdsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @ClassName OrderServiceImpl
 * @Author zhong
 * @Date 2019/12/24 16:42:56
 * @Version 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

   @Autowired
   private OrderDAO orderDAO;

   @Autowired
   private OrderItemDAO orderItemDAO;

   @Autowired
   private CouponDAO couponDAO;

   @Autowired
   private GoodsDAO goodsDAO;

   @Autowired
   private ScanOrderStatusServiceImp scanOrderStatusService;

    /**
     * 增加订单以及订单项
     * 1:减少商品库存
     * 2：修改使用的优惠券的状态为 已使用（"2"）
     * 3：等待用户支付，页面提示用户支付，10分钟不支付则取消订单
     *
     * 3：消息通信
     *      a:发消息通知商户有新订单（websocket）
     *      b:发请求给骑手服务器找骑手，后续业务流程由骑手服务器完成
     *
     * @param order
     * @return void
     * @Author zhong
     * @Date 2019/12/24 16:42:12
     **/
    @Override
    public void add(Order order) {
        String orderId = ZdsUtils.produceId();
        BigDecimal totalPrice = new BigDecimal("0.00");
        BigDecimal totalDiscountedMoney = new BigDecimal("0.00");


        for (OrderItem orderItem : order.getOrderItemList()) {
            orderItem.setId(ZdsUtils.produceId());
            orderItem.setOrderId(orderId);

            String goodsId = orderItem.getGoodsId();
            int nums = orderItem.getNums();
            BigDecimal price = orderItem.getPrice();

            //计算总费用
            totalPrice = totalPrice.add(price);

            //修改商品库存
            goodsDAO.updateGoodsStockById(goodsId,nums*-1);
            //往数据库添加订单项
            orderItemDAO.add(orderItem);
        }

        //修改优惠券状态为已用
        List<Coupon> couponList = order.getCouponList();
        String[] couponIds = new String[couponList.size()];
        for (int i = 0; i < couponIds.length; i++) {
            couponIds[i] = couponList.get(i).getId();
            totalDiscountedMoney = totalDiscountedMoney.add(couponList.get(i).getDiscountAmount());
        }
        couponDAO.updateStatusToUsedBitch(couponIds);


        order.setId(orderId);
        order.setOrderNo("");
        order.setOrderTime(new Date());
        order.setStatus("1");
        order.setDeliveryFee(new BigDecimal("0.00"));
        order.setDiscountedMoney(totalDiscountedMoney);
        order.setTotalMoney(totalPrice);
        order.setOrderTime(new Date());
        //往数据库添加订单
        orderDAO.add(order);

        //添加监听订单状态任务进入队列,等待用户支付
        scanOrderStatusService.addOrder(System.currentTimeMillis()+600000, orderId);

    }

    /**
     * 取消订单
     *
     * @param orderId 订单id
     * @return void
     * @Author zhong
     * @Date 2019/12/25 22:37:36
     **/
    @Override
    public void cancle(String orderId) {
        List<OrderItem> orderItems = orderItemDAO.getListByOrderId(orderId);

        for (OrderItem orderItem : orderItems) {
            String goodsId = orderItem.getGoodsId();
            int nums = orderItem.getNums();
            //返还商品库存
            goodsDAO.updateGoodsStockById(goodsId,nums);
        }

        //修改优惠券状态为已用
        List<Coupon> couponList = couponDAO.getListByOrderId(orderId);
        String[] couponIds = new String[couponList.size()];
        for (int i = 0; i < couponIds.length; i++) {
            couponIds[i] = couponList.get(i).getId();
        }
        couponDAO.updateStatusToNotUseBitch(couponIds);

        orderDAO.updateStatusToCancle(orderId);
    }

    /**
     * 完成订单
     * @Author zhong
     * @Date 2019/12/26 16:01:42
     * @param orderId 订单ID
     * @return void
     **/
    @Override
    public void finish(String orderId) {
        orderDAO.updateStatusToFinish(orderId);
    }

    /**
     * 根据订单ID查询订单
     *
     * @param orderId 订单ID
     * @return com.mayi.zds.entity.Order
     * @Author zhong
     * @Date 2019/12/25 22:39:24
     **/
    @Override
    public Order getById(String orderId) {
        return null;
    }

    /**
     * //TODO 根据条件查询订单
     *
     * @param param
     * @return java.util.List<com.mayi.zds.entity.Order>
     * @Author zhong
     * @Date 2019/12/24 16:35:27
     **/
    @Override
    public List<Order> getListByConditions(OrderQueryParam param) {

        return orderDAO.getListByConditions(param);
    }
}
